package com.zhuiyun.project.api.dukacard.config;
import com.alibaba.fastjson2.JSONObject;
import com.zhuiyun.project.api.coachmanagement.entity.CoachManagement;
import com.zhuiyun.project.api.memberTypeManagement.entity.MemberCardNumber;
import com.zhuiyun.project.api.memberUserManagement.mapper.MemberUserManagementMapper;
import com.zhuiyun.project.api.memberUserManagement.model.MemberUserAndTypeModel;
import com.zhuiyun.project.api.reservation.mapper.ReservationMapper;
import com.zhuiyun.project.api.vipPlan.model.ActionListModel;
import com.zhuiyun.project.utils.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @ClassName MemberTypeController
 * @Description TODO websocket组件
 * @Author WX
 * @Date 2023/11/2 11:36
 **/
@Component
@ServerEndpoint("/wx")
public class WebSocketServer {



    private static Session session; // WebSocket会话


    /**
    * @Author wx
    * @Description 数据连接时方法
    * @Date 2023/12/7 11:37
    * @Return
    * @param session
    */
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WebSocket opened: " + session.getId());
        WebSocketServer.session = session;
        // 调用异步读卡方法
    }

    /**
     * @Author wx
     * @Description 关闭连接
     * @Date 2023/12/7 11:37
     * @Return
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println("WebSocket closed: " + session.getId());
    }

    /**
     * @Author wx
     * @Description 接收数据
     * @Date 2023/12/7 11:37
     * @Return
     * @param session
     */
    @OnMessage // 处理接收到的消息
    public void onMessage(String message, Session session) {
        System.out.println("Message received: " + message);
        try{
            handleWebSocketMessage(message);
        }catch (Exception e){
            e.printStackTrace();
            // 在发生异常时，可以记录日志或者发送错误消息到客户端
            WebSocketServer.sendMessage("Error processing message: " + e.getMessage());
        }

    }

    /**
     * @Author wx
     * @Description 发生错误
     * @Date 2023/12/7 11:37
     * @Return
     * @param throwable
     */
    @OnError // 处理错误
    public void onError(Throwable throwable) {
        System.out.println("失败");
    }

    /**
    * @Author wx
    * @Description 提供发送消息的静态方法
    * @Date 2023/12/7 11:38
    * @Return
    * @param message
    */
    public static void sendMessage(String message) {
        if (session != null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void handleWebSocketMessage(String message) throws IllegalAccessException {
        MemberUserManagementMapper memberUserManagementMapper = SpringContextUtil.getBean(MemberUserManagementMapper.class);
        ReservationMapper reservationMapper = SpringContextUtil.getBean(ReservationMapper.class);
        if (message != null){
            // 将返回的字符串解析为JSONObject
            JSONObject responseJson = JSONObject.parseObject(message);
            if (responseJson.containsKey("customValue") && responseJson.containsKey("readResult")) {
                // 提取 customValue 并命名为 venueUniqueIdentifier
                String venueUniqueIdentifier = responseJson.getString("customValue");
                // 提取 readResult 并命名为 membershipCardNumber
                String membershipCardNumber = responseJson.getString("readResult");
                // 通过租户标识和卡号查询用户信息
                MemberUserAndTypeModel byMembershipCardNumber = memberUserManagementMapper.getByMembershipCardNumber(venueUniqueIdentifier, membershipCardNumber);

                if (byMembershipCardNumber != null){
                    // 判断教练邀请码是否拥有
                    if (byMembershipCardNumber.getInvitationCode() != null &&! byMembershipCardNumber.getInvitationCode().equals("null")){
                        String invitationCode =byMembershipCardNumber.getInvitationCode();
                        // 查询教练信息
                        CoachManagement coachManagement =memberUserManagementMapper.getByInvitationCode(invitationCode,venueUniqueIdentifier);
                        byMembershipCardNumber.setCoachName(coachManagement.getCoachName()) ;
                    }
                }
                // 查询约课信息
                List<ActionListModel> reservationList = reservationMapper.selectListById(venueUniqueIdentifier,membershipCardNumber);
                if (byMembershipCardNumber != null) {
                    MemberCardNumber memberCardNumber = memberUserManagementMapper.selectCardNumberByToday(venueUniqueIdentifier, membershipCardNumber);
                    Integer cardNumber ;
                    if (memberCardNumber != null){
                        cardNumber = memberCardNumber.getCardNumber();
                    }else {
                        cardNumber = 0;
                    }
                    // 将查询结果转换为JSON格式
                    JSONObject memberUserJson = new JSONObject();

                    // 使用反射获取对象的所有字段并放入JSON中
                    Field[] fields = byMembershipCardNumber.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        field.setAccessible(true);
                        memberUserJson.put(field.getName(), field.get(byMembershipCardNumber));
                    }

                    // 添加reservationList到JSON中
                    memberUserJson.put("reservationList", reservationList);
                    memberUserJson.put("cardNumber", cardNumber);
                    // 将JSON格式的查询结果发送到客户端
                    WebSocketServer.sendMessage(memberUserJson.toString());
                }else {
                    // 如果查询结果为null，则返回venueUniqueIdentifier和membershipCardNumber的值
                    JSONObject responseJson2 = new JSONObject();
                    responseJson2.put("venueUniqueIdentifier", venueUniqueIdentifier);
                    responseJson2.put("membershipCardNumber", membershipCardNumber);
                    WebSocketServer.sendMessage(responseJson2.toString());
                }
            }else {
                System.out.println("Message does not contain 'customValue' or 'readResult'.");
            }
        }else {
            System.out.println("Message is null");
        }
    }
}
